<template>
    <div class="time_messagePage flex_column">
        <div class="selectVue flex_between">
            <div class="flex align_center">
                <el-select v-model="userWechatName" placeholder="选择微信AI客服" style="width: 180px;" @change="handleChange">
                    <el-option v-for="item in options" :key="item.id" :label="item.wechatName" :value="item.id"></el-option>
                </el-select>
            </div>
            <div class="flex">
                <!-- <div class="btn" style="width: 120px;">历史发送记录</div> -->
                <div class="btn" @click="toCreate()">创建</div>
            </div>

        </div>

        <!-- 定时消息列表 -->
        <div class="time_messageContent flex_1">
            <el-table :data="list" height="100%" border width="100%" class="center-table">
                <!-- 列表为空 -->
                <div slot="empty" class="flex_column align_center">
                    <img src="../../assets/empty.png" slot="empty" style="width: 313px; height: 172px; margin-bottom: 20px">
                    <span style="color: #101010; font-weight: 600; font-size: 18px">当前列表是空哦~</span>
                    <div style="color: #8F959E; padding-top: 15px">点击右上角的创建，添加您的定时消息吧</div>
                </div>

                <!-- 发送对象 -->
                <el-table-column prop="receiverIds" label="发送对象" width="100" >
                    <template slot-scope="scope">
                        <span style="font-size: 13px; color: #333;">{{ scope.row.receiverIds.split(",").length }}人</span>
                    </template>
                </el-table-column>

                <!-- 发送类型 -->
                <el-table-column prop="repeatTypeStr" label="发送类型" width="100"></el-table-column>

                <!-- 发送时间 -->
                <el-table-column prop="triggerTime" label="发送时间" width="150"></el-table-column>

                <!-- 消息内容 -->
                <el-table-column prop="msgContent" label="消息内容">
                    <template slot-scope="scope">
                        <div v-for="(item, index) in scope.row.msgList" :key="index" style="margin-bottom: 10px; font-size: 13px;text-align: left;">
                            <img :src="item.msgContent" style="width: 60px; height: 60px; cursor: pointer;"  v-if="item.msgType===2" @click="imgUrl=item.msgContent; dialogTableVisible80=true">
                            <span v-if="item.msgType===1" style="font-size: 13px;">文本消息：{{ item.msgContent }}</span>
                            <span v-if="item.msgType===3" style="font-size: 13px;">AI提示词：{{ item.msgContent }}</span>
                        </div>
                    </template>
                </el-table-column>

                <!-- 状态 -->
                <el-table-column prop="status" label="状态" width="100">
                    <template slot-scope="scope">
                        <div class="state" :class="{active: scope.row.status}" @click="handleAiStatus(scope.row)">
                            <div class="dot dot_right" v-if="scope.row.status===1"></div>
                            <div class="dot dot_left" v-else></div>
                        </div>
                    </template>
                </el-table-column>

                <!--  查看 删除 -->
                <el-table-column label="操作" width="150">
                    <template slot-scope="scope">
                        <div class="flex_center">
                            <el-button size="mini" type="manage" @click="handleManage(scope.row)">管理</el-button>
                            <el-button size="mini" type="delete" @click="handleDelete(scope.row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="paginationVue flex_center align_center">
            <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"  @current-change="handlePageChange"></el-pagination>
        </div>

        <!-- 创建定时消息 -->
        <el-dialog :visible.sync="dialogTableVisible" :show-close="false" :center="true" top="4vh" @close="close">
            <div class="dialogVue flex_column">
                <!-- 顶部步骤 -->
                <div class="stepVue flex_center">
                    <div class="flex_column align_center">
                        <div class="dot" :class="{active: current===1}">1</div>
                        <span :class="{textActive: current===1}">选择接收消息对象</span>
                    </div>
                    <div class="line"></div>
                    <div class="flex_column align_center">
                        <div class="dot" :class="{active: current===2}">2</div>
                        <span :class="{textActive: current===2}">设置消息内容</span>
                    </div>
                    <div class="line"></div>
                    <div class="flex_column align_center">
                        <div class="dot" :class="{active: current===3}">3</div>
                        <span :class="{textActive: current===3}">完成</span>
                    </div>
                </div>

                <!-- 第一步 -->
                <template v-if="current===1">
                    <!-- 搜索 -->
                    <div class="selectVue flex_between margin20">
                        <div class="flex">
                            <el-select v-model="classflyName" placeholder="选择分组" style="width: 180px; margin-left: 10px;" @change="classflyChange" clearable>
                                <el-option v-for="item in classflyList" :key="item.name" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                            <el-select v-model="tagName" placeholder="选择标签" style="width: 180px; margin-left: 10px;" @change="tagChange" clearable>
                                <el-option v-for="item in tagList" :key="item" :label="item" :value="item"></el-option>
                            </el-select>
                            <el-select v-model="chatName" placeholder="聊天类型" style="width: 180px; margin-left: 10px;" @change="chatChange" clearable>
                                <el-option v-for="item in chatTypes" :key="item.type" :label="item.name" :value="item"></el-option>
                            </el-select>
                        </div>
                        <div class="flex">
                            <el-input v-model="key" placeholder="搜索关键字" style="margin-left: 10px; width: 180px;" :clearable="true" @clear="clearFun" @input="searchFun"></el-input>
                        </div>
                    </div>

                    <div class="flex">
                        <div class="selectAll" :class="{selectActive: isAll}"  @click="selectAll">
                            <span class="el-icon-loading" v-if="isLoading"></span>
                            <span v-else>{{ isAll ? "清空已选择" : "一键选择所有好友" }}</span>
                        </div>
                        <div class="selectAll" style="margin-left: 10px" :class="{selectActive: isAll}"  @click="selectCurrentPage">
                            <span>选择当前页面</span>
                        </div>
                    </div>

                    <!-- 选择对象 -->
                    <div class="bodyVue margin10">
                        <div class="bodyInner flex flex_wrap">
                            <div class="ver flex align_center" v-for="(ver, i) in friendList" :key="i" :class="{active: JSON.stringify($store.state.selectList).includes(JSON.stringify(ver))}" @click="selectFun(ver)">
                                <img src="../../assets/weChat.png" style="width: 38px; height: 38px;" v-if="ver.type===0">
                                <img src="../../assets/weChat_group.png" style="width: 38px; height: 38px;" v-if="ver.type===1">
                                <span class="line-1">{{ver.type===0 ? ver.friendWechatName : ver.groupName}} </span>
                            </div>
                        </div>
                        <!-- 列表为空 -->
                        <div slot="empty " class="flex_column align_center" style="padding-top: 100px;" v-if="isEmpty">
                            <img src="../../assets/empty.png" slot="empty" style="width: 313px; height: 172px; margin-bottom: 15px">
                            <span style="color: #999; font-size: 14px">无可操作对象哦~</span>
                        </div>
                    </div>

                    <div class="selectedVue">
                        <el-tag v-for="tag in $store.state.selectList" :key="tag.name" closable type="info" size="mini" @close="handleClose(tag)">{{tag.type===0 ? tag.friendWechatName : tag.groupName}}</el-tag>
                    </div>

                    <!-- 分页 -->
                    <div class="paginationVue flex_between align_center">
                        <el-pagination background layout="total, prev, pager, next" :total="friendTotal"  :page-size="friendPageSize"  @current-change="handleCurrentChange"></el-pagination>
                        <div class="flex align_center">
                            <div class="cancel" @click="close">取消</div>
                            <div class="create" @click="nextFun(1)">下一步</div>
                        </div>
                    </div>
                </template>

                <!-- 第二步 -->
                <template v-if="current===2">
                    <div class="label">已选对象</div>
                    <div class="selectedVue" style="margin-top: 0;">
                        <el-tag v-for="tag in $store.state.selectList" :key="tag.name" closable type="info" size="mini" @close="handleClose(tag)">{{tag.type===0 ? tag.friendWechatName : tag.groupName}}</el-tag>
                    </div>


                    <div class="contentVue" ref="chatBody">
                        <div class="label">发布日期</div>
                        <div class="radioVue">
                            <div class="flex">
                                <el-radio v-model="radio" :label="item.key" v-for="(item, index) in repeatTypeList" :key="index">{{ item.name }}</el-radio>
                                <el-radio v-model="radio" :label="4">立即发送</el-radio>
                            </div>
                            <div class="flex align_center" style="padding-top: 15px;" v-if="radio==1">
                                <div class="h8">选择发布日期</div>
                                <!-- 特定日期 -->
                                <div class="block">
                                    <el-date-picker
                                        v-model="date"
                                        type="date"
                                        @change="handleDate"
                                        format="yyyy-MM-dd"
                                        :picker-options="disableOptions"
                                        placeholder="选择日期">
                                    </el-date-picker>
                                </div>
                                <div style="width: 50px;"></div>
                                <div class="h8">发布时间</div>
                                <el-input v-model="time" placeholder="输入时间" style="width: 220px;"></el-input>
                                <span style="padding-left: 10px;color: #d81e06; font-size: 12px;">输入时间时注意时间格式，例如09:00(时分之间用英文冒号隔开)</span>
                            </div>
                            <div class="flex align_center" style="padding-top: 15px;" v-if="radio==2">
                                <div class="h8">发布时间</div>
                                <el-input v-model="time" placeholder="输入时间" style="width: 220px;"></el-input>
                                <span style="padding-left: 10px;color: #d81e06; font-size: 12px;">输入时间时注意时间格式，例如09:00(时分之间用英文冒号隔开)</span>
                            </div>
                            <div style="padding-top: 15px;" v-if="radio==3">
                                <div class="flex align_center">
                                    <div class="h8">发布日期</div>
                                    <div class="week" :class="{active: selectDays.includes(o)}" v-for="(o, i) in days" :key="i" @click="selectWeekFun(o)">{{ o }}</div>
                                </div>
                                <div class="flex align_center"  style="margin-top: 15px;">
                                    <div class="flex align_center">
                                        <div class="h8">发布时间</div>
                                        <el-input v-model="time" placeholder="输入时间" style="width: 220px;"></el-input>
                                        <span style="padding-left: 10px;color: #d81e06; font-size: 12px;">输入时间时注意时间格式，例如09:00(时分之间用英文冒号隔开)</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="contentItem" v-for="(item, index) in contentList" :key="index">
                            <div class="label">发布内容</div>
                            <div class="radioVue">
                                <div class="flex_between">
                                    <div class="flex">
                                        <el-radio v-model="contentList[index].radio20" label="1">自定义文本内容</el-radio>
                                        <el-radio v-model="contentList[index].radio20" label="2">自定义图片内容</el-radio>
                                    </div>
                                    <span class="el-icon-close" style="font-size: 18px; cursor: pointer;" v-if="index!=0" @click="removeFun(index)"></span>
                                </div>

                                <!-- 文本 -->
                                <template v-if="contentList[index].radio20=='1'">
                                    <div class="flex_between align_cneter" style="margin-top: 20px;">
                                        <div class="flex align_center">
                                            <span style=" color: #666; font-size: 12px; padding-right: 10px;">使用AI生成内容</span>
                                            <el-switch v-model="contentList[index].isAi" active-color="#0147fd" inactive-color="#999"></el-switch>
                                        </div>
                                        <div class="flex align_center" v-if="contentList[index].isAi">
                                            <span style=" color: #666; font-size: 12px; padding-right: 10px;">每个接收都生成差异化的内容</span>
                                            <el-switch v-model="contentList[index].isDifferent" active-color="#0147fd" inactive-color="#999"></el-switch>
                                        </div>
                                    </div>

                                    <div class="flex_between align_center">
                                        <textarea placeholder="请输入您要群发的内容" v-if="!contentList[index].isAi" v-model="contentList[index].message" :maxlength="2000"></textarea>
                                        <textarea placeholder="请大概描述你需要AI生成的内容需求" v-if="contentList[index].isAi && !contentList[index].isDifferent" v-model="contentList[index].ai_request"></textarea>
                                        <div class="arrow relative" v-if="contentList[index].isAi && !contentList[index].isDifferent" @click="getAiMsg(item)">
                                            <img src="../../assets/arrow.png" title="点击AI生成" style="width: 80px; height: 60px">
                                            <div class="absolute_auto text_center" style="color: #fff; font-size: 12px; width: 100%; font-weight: 600; line-height: 1;">
                                                <span class="el-icon-loading" v-if="contentList[index].isLoading" style="color: #fff"></span>
                                                <span v-else style="color: #fff;">点击生成</span>
                                            </div>
                                        </div>
                                        <textarea placeholder="AI生成内容预览" v-if="contentList[index].isAi && !contentList[index].isDifferent" v-model="contentList[index].aiMessage"></textarea>
                                        <textarea placeholder="输入提示词，AI根据提示词生成内容" v-if="contentList[index].isAi && contentList[index].isDifferent"  v-model="contentList[index].word"></textarea>
                                    </div>
                                </template>
                                <!-- 图片 -->
                                <template v-if="contentList[index].radio20=='2'">
                                    <div class="lii relative text_center" style="line-height: 100px;">
                                        <input ref="clearRef" class="fileBtn" type="file" id="fileupload" accept="image/*" @change="fileChange($event, index)"/>
                                        <img :src="contentList[index].img" style="width: 100%; height: 100%;" class="absolute_auto" v-if="contentList[index].img">
                                        <template v-else>
                                            <span class="el-icon-loading" v-if="loading"></span>
                                            <img src="../../assets/upload.png" style="width: 38px; height: 38px; font-size: 18px;" class="absolute_auto" v-else>
                                        </template>   
                                    </div>
                                </template>
                            </div>
                        </div>
                        <div class="again margin10" @click="againFun" v-if="contentList.length<6">再加一条</div>
                    </div>
                    <div class="paginationVue flex_end align_center margin30">
                        <div class="cancel" @click="close">取消</div>
                        <div class="create" @click="nextFun(2)">下一步</div>
                    </div>
                </template>

                <template v-if="current===3">
                    <div class="label">已选对象</div>
                    <div class="selectedVue" style="margin-top: 0;">
                        <el-tag v-for="tag in $store.state.selectList" :key="tag.id" closable type="info" size="mini" @close="handleTag(tag)">{{tag.type===0 ? tag.friendWechatName : tag.groupName}}</el-tag>
                    </div>
                    <div class="inner flex_1">
                        <div class="innerLi" v-if="radio==1">发布时间： {{ date }} {{ time }}</div>
                        <div class="innerLi" v-if="radio==2">发布时间： 每天 {{ time }}</div>
                        <div class="innerLi flex align_center" v-if="radio==3">
                            <span>发布时间：</span>
                            <div class="week" v-for="(o, i) in selectDays" :key="i">{{ o }}</div>
                            <span>每天 {{ time }}</span>
                        </div>
                        <div class="innerLi" v-if="radio==4">发布时间： 立即发送</div>
                        <div class="innerContent" v-for="(item, index) in contentList" :key="index">
                            <span v-if="item.isDifferent">生成内容的提示词：</span>
                            <span v-else>发布内容：</span>
                            <span v-if="item.isDifferent">{{ item.word }}</span>
                            <template v-else>
                                <span v-if="item.radio20==1">{{ item.isAi ? item.aiMessage : item.message }}</span>
                                <img v-if="item.radio20==2" :src="item.imgUrl" style="width: 100px; height: 100px;">
                            </template>
                        </div>
                    </div>
                    <div class="paginationVue flex_end align_center margin10">
                        <div class="cancel" @click="current=2">上一步</div>
                        <div class="create" @click="submitFun()">完成</div>
                    </div>
                </template>
            </div>
        </el-dialog>

        <preview :dialogTableVisible80="dialogTableVisible80" :previewUrl="imgUrl" @beforeClose="dialogTableVisible80=false"></preview>
    </div>
</template>

<script>
import { toast, formatTime } from '@/common/tools'
import { post } from '@/common/request'
import preview from '@/components/preview.vue'
export default {
    components: {
        preview
    },
    data(){
        return {
            list: [],
            total: 0,
            dialogTableVisible: false,
            dialogTableVisible80: false,
            current: 1,
            value: "",
            key: "",
            diaTotal: 0,
            radio: 1,
            radio20: "1",
            date: "",
            time: "",
            isAi: false,
            activeName: "1",
            options: [],
            pageNum: 1,
            pageSize: 10,
            friendList: [],
            days: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            selectDays: [],
            receiverIds: "",
            repeatTypeList: [],
            message: "",
            aiMessage: "",
            ai_request: "",
            weChatId: "",
            img: "",
            imgUrl: "",
            friendPageNum: 1,
            friendPageSize: 32,
            friendTotal: 0,
            disableOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            },
            isLoading: false,
            classflyName: "",
            classflyId: "",
            classflyList: [],
            tagName: "",
            isEmpty: false,
            isAll: false,
            applicationId: "",
            userWechatName: "",
            isLoading: false,
            tagList: ["高意向","中意向","低意向","了解产品详情", "询问价格", "询问使用方法", "询问发货时间", "询问售后服务", "非常满意", "满意", "一般", "不满意", "非常不满意", "产品质量", "发货时间", "售后服务", "使用问题", "价格问题", "新客户", "忠实客户", "活跃", "潜在", "流失"],
            contentList: [
                {
                    radio20: "1",
                    isAi: false,
                    message: "",
                    ai_request: "",
                    aiMessage: "",
                    isLoading: false,
                    img: "",
                    imgUrl: "",
                    isDifferent: false,
                    word: ""
                }
            ],
            loading: false,
            chatType: "",
            chatTypes: [{name: "私聊", type: 0}, {name: "群聊", type: 1}],
            chatName: "",
        }
    },
    created(){
        this.getWeChatList()
        this.getRepeatTypeList()
        this.getClassflyList()
    },

    watch: {
        key(){
            if(!this.key) {
                this.friendPageNum = 1
                this.getFriendList()
            }
        }
    },
    methods: {
        clearFun(){
            this.friendPageNum = 1
            this.getFriendList()
        },

        formatTimeFun(value){
            if(!value) return
            return formatTime(value*1000, "YMDHMS")
        },

        // 管理定时消息
        handleManage(item){
            console.log(item)
            this.dialogTableVisible = true
            this.getFriendList()
            this.radio = item.repeatType
            this.radio20 = String(item.msgType)
            this.message = item.msgContent
            this.isAi = false
            if(item.repeatType===1) {
                this.date = item.triggerTime.split(" ")[0]
                this.time = item.triggerTime.split(" ")[1]
            }
            if(item.repeatType===2) {
                this.time = item.triggerTime
            }
            if(item.repeatType===3) {
                this.selectDays = item.dayStr.split(",")
                this.time = item.triggerTime
                console.log(this.selectDays, this.time)
            }
        },

        // 获取分组列表
        getClassflyList(){
            this.$post("/front/wechat/friend/categoryList").then(res=>{
                if(res.data.code===0) {
                    this.classflyList = res.data.obj
                    console.log(this.classflyList)
                }
            })
        },

        againFun(){
            this.contentList.push({
                radio20: "1",
                isAi: false,
                message: "",
                ai_request: "",
                aiMessage: "",
                isLoading: false,
                img: "",
                imgUrl: "",
                isDifferent: false,
                word: ""
            })
            this.scrollToBottom()
        },

        removeFun(index){
            this.contentList = this.contentList.slice(0, index).concat(this.contentList.slice(index + 1));
        },

        searchFun(){
            this.friendPageNum = 1
            this.getFriendList()
        },

        selectCurrentPage(){
            for(let i=0; i<this.friendList.length; i++) {
                if(!JSON.stringify(this.$store.state.selectList).includes(JSON.stringify(this.friendList[i]))) {
                    this.$store.state.selectList.push(this.friendList[i])
                }
            }
        },


        getAiMsg(item){
            if(!item.ai_request) return toast(1, "请大概描述你需要生成的内容需求")
            if(item.isLoading) return
            item.isLoading = true
            this.options.forEach(o=>{
                if(o.id==this.weChatId) {
                    console.log("this.applicationId = o.applicationId")
                    this.applicationId = o.applicationId
                }
            })
            this.$post("/front/userWechat/returnModelAnswer", {
                applicationId: this.applicationId,
                message: item.ai_request
            }).then(res=>{
                if(res.data.code===0) {
                    console.log(res)
                    item.isLoading = false
                    item.aiMessage = res.data.obj
                }else {
                    item.isLoading = false
                    toast(1, res.data.msg)
                }
            })
        },
        chatChange(e){
            console.log(e)
            if(!e) {
                this.chatType = ""
                this.friendPageNum = 1
                this.getFriendList()
                return
            }
            this.chatName = e.name
            this.chatType = e.type
            this.friendPageNum = 1
            this.getFriendList()
        },

        classflyChange(e){
            this.classflyId = e
            this.friendPageNum = 1
            this.getFriendList()
        },

        tagChange(e){
            this.tagName = e
            this.friendPageNum = 1
            this.getFriendList()
        },

        handleDate(e){
            let timestamp = new Date(e).getTime()
            this.date = formatTime(timestamp, "YMD")
        },

        nextFun(index){
            if(index===1) {
                if(this.$store.state.selectList.length===0) return toast(1, "请至少选择一个接收消息对象")
                this.current = 2
            }
            if(index===2) {
                console.log(this.radio, this.date)
                if(this.radio==1 && !this.date) return toast(1, "请选择日期")
                if(this.radio==1 && !this.time) return toast(1, "请选择时间")
                if(this.radio==2 && !this.time) return toast(1, "请选择时间")
                if(this.radio==3 && !this.time) return toast(1, "请选择时间")
                if(this.radio==3 && !this.selectDays.length===0) return toast(1, "请选择周期")
                console.log(this.loading,"kkkk")
                if(this.loading) return toast(1, "图片上传中，请稍后...")
                for(let j=0; j<this.contentList.length; j++){
                    let msgContent = this.contentList[j].isDifferent ? this.contentList[j].word : (this.contentList[j].radio20==2 ? this.contentList[j].imgUrl : (this.contentList[j].isAi ? this.contentList[j].aiMessage : this.contentList[j].message))
                    if(!msgContent) return toast(1, "消息内容不正确")
                }
                this.current = 3
            }
        },

        selectAll(){
            if(this.isAll) {
                this.isAll = false
                this.$store.state.selectList = []
                return
            }
            this.$store.state.selectList = this.friendList
            // this.isAll = true
            this.isLoading = true
            this.$post("/front/wechat/friend/friendList", {
                pageNum: 1,
                pageSize: 10000,
                userWechatPrimaryId: this.weChatId,
                userWechatName: this.userWechatName,
                blacklist:0,
                categoryId: this.classflyId,
                tag: this.tagName,
                content: this.key,
                type: this.chatType
            }).then(res=>{
                if(res.data.code===0) {
                    this.$store.state.selectList = res.data.obj.list
                    this.isAll = true
                    this.isLoading = false
                }
                this.isLoading = false
            })

            // this.classflyId = ""
            // this.tagName = ""
            // this.classflyName = ""
            // this.key = ""
            // this.getFriendList()
            // this.isLoading = true
            // this.$post("/front/wechat/friend/friendList", {
            //     pageNum: 1,
            //     pageSize: 10000,
            //     userWechatPrimaryId: this.weChatId,
            //     userWechatName: this.userWechatName,
            //     blacklist:0
            // }).then(res=>{
            //     if(res.data.code===0) {
            //         this.$store.state.selectList = res.data.obj.list
            //         this.isAll = true
            //         this.isLoading = false
            //     }
            //     this.isLoading = false
            // })
        },

        toCreate(){
            if(this.options.length===0)  return toast(1, "请先创建并绑定微信")
            this.dialogTableVisible = true
            this.getFriendList()
        },

        close(){
            this.dialogTableVisible = false
            this.date = ""
            this.time = ""
            this.message = ""
            this.aiMessage = ""
            this.ai_request = ""
            this.current = 1
            this.img = ""
            this.radio = 1
            this.radio20 = "1"
            this.friendList = []
            this.selectDays = []
            this.contentList = [{
                radio20: "1",
                isAi: false,
                message: "",
                ai_request: "",
                aiMessage: "",
                isLoading: false,
                imgUrl: "",
                img: "",
                isDifferent: false,
                word: ""
            }]
            this.isAll = false
            this.$store.state.selectList = []
            if(this.$refs.clearRef && this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
        },

        // 定时消息重复类型
        getRepeatTypeList(){
            this.$post("/front/timedMessage/repeatTypeList").then(res=>{
                console.log(res)
                this.repeatTypeList = res.data.obj
            })
        },

        // 获取定时消息列表
        getList(){
            this.$post("/front/timedMessage/timedMessageList", {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                weChatId: this.weChatId
            }).then(res=>{
                if(res.data.code===0) {
                    this.list = res.data.obj.list
                    this.total = res.data.obj.total
                }
            })
        },

        // 定时状态消息开关
        handleAiStatus(item){
            console.log(item)
            if(item.repeatType==1) {
                let triggerTime = new Date(item.triggerTime).getTime()
                console.log(triggerTime)
                let timestamp = new Date().getTime()
                console.log(timestamp)
                if(timestamp>=triggerTime) return toast(1, "该任务已过期，无法重新启动")
            }
            this.$alert(`确认${item.status===1?"关闭":"开启"}的定时消息?`,  `${item.status===1?"关闭":"开启"}定时消息`, {
                confirmButtonText: '确定',
                confirmButtonClass: 'confirmButtonClass',
                cancelButtonText: '取消',
                showCancelButton: true,
                showClose: false,
                callback: action => {
                    if(action==="confirm") {
                        //AI自动回复开关代码
                        let url = item.status === 1 ? "/front/timedMessage/disableTimedMessage" : "/front/timedMessage/enableTimedMessage"
                        this.$post(url, {
                            id: item.id
                        }).then(res=>{
                            if(res.data.code===0) {
                                toast(0, item.status===0?"定时消息已开启":"定时消息已关闭")
                                this.getList()
                            } else {
                                toast(1, res.data.msg)
                            }
                        })
                    }
                }
            });
        },

        handleChange(e){
            this.weChatId = e
            this.options.forEach(item=>{
                if(item.id==e) {
                    this.userWechatName = item.wechatName
                }
            })
            window.sessionStorage.setItem("currentUserWechatName", this.userWechatName)
            window.sessionStorage.setItem("currentWeChatId", this.weChatId)
        },

        // 查询微信列表
        getWeChatList(){
            this.$post("/front/userWechat/wechatList").then(res=>{
                if(res.data.code===0) {
                    this.options = res.data.obj.list.filter(o=>{
                        return o.wechatName
                    })
                    if(this.options.length===0) return
                    let weChatId = window.sessionStorage.getItem("currentWeChatId")
                    let userWechatName = window.sessionStorage.getItem("currentUserWechatName")
                    this.weChatId = weChatId ? Number(weChatId) : this.options[0].id
                    this.userWechatName =  userWechatName || this.options[0].wechatName,
                    this.getList()
                }
            })
        },

        // 获取好友列表
        getFriendList(){
            this.$post("/front/wechat/friend/friendList", {
                pageNum: this.friendPageNum,
                pageSize: this.friendPageSize,
                userWechatPrimaryId: this.weChatId,
                categoryId: this.classflyId,
                tag: this.tagName,
                content: this.key,
                userWechatName: this.userWechatName,
                blacklist: 0,
                type: this.chatType
            }).then(res=>{
                if(res.data.code===0) {
                    this.friendList = res.data.obj.list
                    this.isEmpty = res.data.obj.list.length ===0
                    this.friendTotal = res.data.obj.total
                }
            })
        },

        // 滑动到聊天最底部
        scrollToBottom(){
            this.$nextTick(()=>{
                let dom = this.$refs.chatBody
                console.log(dom)
                dom.scrollTo({ top: dom.scrollHeight, behavior: 'smooth' });
            })
        },

        clearFun(){
            this.friendPageNum = 1
            this.getFriendList()
        },

        handlePageChange(val){
            console.log(`当前页: ${val}`);
            this.pageNum = val
            this.getList()
        },

        // 好友分页
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.friendPageNum = val
            this.getFriendList()
        },

        selectWeekFun(o){
            if(this.selectDays.includes(o)) {
                this.selectDays = this.selectDays.filter(item=>{
                    return item != o
                })
            }else{
                this.selectDays.push(o)
            }
        },

        fileChange(event, index){
            console.log(index)
            this.contentList[index].imgUrl = ""
            const file = event.target.files[0];
            this.contentList[index].img = this.getFileUrl(file)
            let formData = new FormData()
            formData.append("file", file)
            if(this.loading) return toast(1, "图片上传中，请稍后...")
            this.loading = true
            post("/front/search/uploadImage", formData).then(res=>{
                if(this.$refs.clearRef && this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
                this.loading = false
                if(res.data.code===0) {
                    this.contentList[index].imgUrl = res.data.obj
                    this.img = res.data.obj
                    console.log(this.contentList[index].imgUrl)
                }
            })
        },

        // 创建定时消息
        submitFun(){
            let array = []
            let receiverIds = ""
            for(let i=0; i<this.$store.state.selectList.length; i++){
                array.push(this.$store.state.selectList[i].id)
            }
            receiverIds = array.join(",")
            let msgList = []
           
            
            for(let j=0; j<this.contentList.length; j++){
                let obj = {
                    msgType: this.contentList[j].isDifferent ? 3 :  this.contentList[j].radio20,
                    msgContent: this.contentList[j].isDifferent ? this.contentList[j].word : (this.contentList[j].radio20==2 ? this.contentList[j].imgUrl : (this.contentList[j].isAi ? this.contentList[j].aiMessage : this.contentList[j].message))
                }
                msgList.push(obj)
                console.log("kkk", msgList)
            }
            if(this.radio==4) {
                var timestamp = new Date().getTime() + 60 * 1000
                console.log(timestamp)
                var date = formatTime(timestamp, "YMDHM")
                console.log(date,"ooooooo")
            }
            console.log(this.radio,"jjjj")
            post("/front/timedMessage/addTimedMessage", {
                receiverIds,   //接收者ID
                wechatId: this.weChatId,
                repeatType: this.radio==4 ? 1 : this.radio, //重复类型
                dayStr: this.radio==3 ? this.selectDays.join(",") : "",   // 周循环
                triggerTime: this.radio==4 ? date: ["", this.date+ " " + this.time, this.time, this.time][this.radio],    //触发时间
                status: 1,
                msgList: msgList
            }).then(res=>{
                if(res.data.code===0) {
                    toast(0, "创建成功")
                    this.close()
                    this.getList()
                }else{
                    toast(1, res.data.msg)
                }
            })
        },

        // 删除定时消息
        handleDelete(item){
            console.log(item)
            this.$alert(`确认删除该定时消息?`, '删除定时消息', {
                confirmButtonText: '确定',
                confirmButtonClass: 'confirmButtonClass',
                cancelButtonText: '取消',
                showCancelButton: true,
                showClose: false,
                callback: action => {
                    console.log(action)
                    if(action==="confirm") {
                        //删除微信代码
                        this.$post("/front/timedMessage/delTimedMessage", {
                            id: item.id
                        }).then(res=>{
                            if(res.data.code===0) {
                                toast(0, "删除成功")
                                this.pageNum = 1
                                this.getList()
                            } else {
                                toast(1, res.data.msg)
                            }
                        })
                    }
                }
            });
        },

        getFileUrl(file) {
            var url;
            var agent = navigator.userAgent;
            if (agent.indexOf("MSIE") >= 1 || agent.indexOf("NET")!=-1) {
                url = window.URL.createObjectURL(file);
            } else if (agent.indexOf("Firefox") > 0) {
                url = window.URL.createObjectURL(file);
            } else if (agent.indexOf("Chrome") > 0) {
                url =window.webkitURL.createObjectURL(file);
            }
            return url;
        },

        handleClose(tag) {
            console.log(tag)
            this.$store.state.selectList.splice(this.$store.state.selectList.indexOf(tag), 1);
        },

        selectFun(item){
            console.log(JSON.stringify(this.$store.state.selectList).includes(JSON.stringify(item)))
            if(JSON.stringify(this.$store.state.selectList).includes(JSON.stringify(item))) {
                this.$store.state.selectList = this.$store.state.selectList.filter(o=>{
                    return item.id != o.id
                })
            }else{
                this.$store.state.selectList.push(item)
            }
        },
    }
}
</script>

<style lang="less" scoped>
:deep(.center-table td),
:deep(.center-table th) {
    text-align: center !important;
    height: 85px !important;
}
:deep(.center-table th) {
    background: #f5f5f5 !important;
    height: 48px !important;
}
:deep(.el-table .cell) {
    font-size: 13px !important;
}
:deep(.el-button--delete) {
    background: #d81e06;
    span {
        color: #fff !important;
    }
}
:deep(.el-button--manage) {
    background: #0147fd;
    span {
        color: #fff !important;
    }
}
:deep(.el-radio__input.is-checked .el-radio__inner) {
    border-color: #0147fd;
    background: #0147fd;
}
:deep(.el-radio__input.is-checked+.el-radio__label) {
    color: #0147fd;
}
:deep(.el-dialog) {
    width: 1090px;
    height: 90vh;
}
:deep(.el-dialog__title) {
    color: #111;
    font-size: 16px;
    font-weight: 600;
}
:deep(.el-dialog__header) {
    padding: 0;
}
:deep(.el-dialog__body) {
    padding: 0;
}
:deep(.el-tabs__item.is-active) {
    color: #0147fd;
    font-weight: 600;
}
:deep(.el-tabs__item:hover) {
        color: #0147fd !important;
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner) {
    background: #0147fd !important;
    border-color: #0147fd !important;
}
:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
    background: #0147fd !important;
    border-color: #0147fd !important;
}
:deep(.el-tag--info) {
    margin-right: 5px;
    margin-bottom: 5px;
}
:deep(.el-icon-circle-close) {
    font-size: 18px !important;
    color: #409EFF !important;
}
.time_messagePage {
    width: 100%;
    height: 100%;
    padding: 20px 20px 0;
    .state {
        width: 40px;
        height: 20px;
        background: #AAA;
        border-radius: 10px;
        margin: 0 auto;
        position: relative;
        cursor: pointer;
        .dot {
            width: 16px;
            height: 16px;
            background: #fff;
            border-radius: 50%;
            position: absolute;
        }
        .dot_left {
            left: 2px;
            top: 2px;
        }
        .dot_right {
            right: 2px;
            top: 2px;
        }
    }
    .active {
        background: #0147fd;
    }
    .selectVue {
        width: 100%;
        height: 36px;
        .btn {
            width: 80px;
            height: 40px;
            background: #0147fd;
            border-radius: 4px;
            text-align: center;
            line-height: 40px;
            color: #fff;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            margin-left: 10px;
        }
    }
    .time_messageContent {
        width: 100%;
        margin-top: 20px;
    }
    .paginationVue {
        width: 100%;
        height: 60px;
    }
}

.dialogVue {
    width: 100%;
    height: 90vh;
    padding: 20px 20px 0;

    .stepVue {
        width: 100%;
        .dot {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #EEE;
            line-height: 25px;
            text-align: center;
            color: #999;
            margin-bottom: 10px;
        }
        .active {
            background: #0147fd;
            color: #fff;
        }
        .line {
            width: 150px;
            height: 1px;
            background: #EEE;
            margin-top: 12px;
        }
        span {
            color: #999;
            font-size: 12px;
        }
        .textActive {
            color: #0147fd;
            font-weight: 600;
        }
    }

    .label {
        color: #666;
        font-size: 12px;
        padding: 20px 0 10px 0;
    }

    .selectAll {
        width: 252px;
        height: 50px;
        border: 1px solid #f5f5f5;
        margin-top: 15px;
        cursor: pointer;
        border-radius: 4px;
        line-height: 50px;
        color: #81868e;
        text-align: center;
    }
    .selectActive {
        border: 1px solid #0147fd;
        background: rgba(1,71,253, 0.1);
    }

    .bodyVue {
        width: 100%;
        height: calc(80vh - 174px);
        overflow: scroll;
        .bodyInner {
            width: 100%;
            .ver {
                width: 252px;
                height: 50px;
                border: 1px solid #f5f5f5;
                margin-bottom: 10px;
                margin-right: 10px;
                cursor: pointer;
                padding: 0 10px;
                border-radius: 4px;
                span {
                    color: #81868e;
                    padding-left: 10px;
                }
            }
            .active {
                border: 1px solid #0147fd;
                background: rgba(1,71,253, 0.1);
            }
        }
    }
    .bodyVue::-webkit-scrollbar {
        width: 0;
        height: 0;
    }

    .contentVue {
        flex: 1;
        overflow: scroll;
    }
    .contentVue::-webkit-scrollbar {
        width: 0;
        height: 0;
    }

    .again {
        width: 100%;
        height: 50px;
        text-align: center;
        line-height: 50px;
        background: #f5f5f5;
        cursor: pointer;
    }
    .radioVue {
        width: 100%;
        flex: 1;
        padding: 15px;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
        .h8 {
            color: #666;
            font-size: 12px;
            padding-right: 10px;
        }
        .arrow {
            width: 80px;
            height: 60px;
            margin: 0 20px;
            cursor: pointer;
        }
        .lii {
            width: 100px;
            height: 100px;
            background: #f5f5f5;
            border-radius: 4px;
            margin-top: 20px;
            cursor: pointer;
            .fileBtn {
                width: 100%;
                height: 100%;
                position: absolute;
                left: 0;
                top: 0;
                opacity: 0;
                cursor: pointer;
                z-index: 98;
                border: none;
                outline: none;
            }
        }
    }

    .week {
        width: 80px;
        height: 32px;
        border: #DCDFE6 1px solid;
        margin-right: 10px;
        border-radius: 4px;
        line-height: 30px;
        text-align: center;
        color: #999;
        cursor: pointer;
    }

    .active {
        background: #0147fd;
        color: #fff;
    }

    textarea {
        flex: 1;
        height: 100px;
        border: #DCDFE6 1px solid;
        display: block;
        box-sizing: border-box;
        resize: none;
        border-radius: 4px;
        margin-top: 20px;
        line-height: 1.4;
        font-family: PingFangSC, PingFang SC;
        padding: 10px;
        font-size: 13px;
    }
    textarea::-webkit-scrollbar {
        width: 0;
        height: 0;
    }
    ::-webkit-input-placeholder { /* WebKit browsers */
        color: #AAA;
        font-size: 13px;
        font-family: PingFangSC, PingFang SC;
    }
    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
        color: #AAA;
        font-size: 13px;
        font-family: PingFangSC, PingFang SC;
     }
    ::-moz-placeholder { /* Mozilla Firefox 19+ */
        color: #AAA;
        font-size: 13px;
        font-family: PingFangSC, PingFang SC;
    }
    :-ms-input-placeholder { /* Internet Explorer 10+ */
        color: #AAA;
        font-size: 13px;
        font-family: PingFangSC, PingFang SC;
    }

    .inner {
        width: 100%;
        border: 1px solid #DCDFE6;
        margin-top: 20px;
        border-radius: 4px;
        padding: 20px;
        .innerContent {
            padding-top: 15px;
            line-height: 1.4;
        }
    }

    .searchVue {
        width: 100%;
        height: 40px;
        .btn {
            width: 80px;
            height: 40px;
            text-align: center;
            line-height: 40px;
            border-radius: 5px;
            background: #0147fd;
            color: #fff;
            margin-left: 10px;
            cursor: pointer;
        }
    }

    .content {
        width: 100%;
        margin-top: 20px;

    }
    .selectedVue {
        width: 100%;
        height: 100px;
        border: 1px solid #DCDFE6;
        margin-top: 10px;
        border-radius: 4px;
        padding: 5px;
        overflow: scroll;
    }
    .selectedVue::-webkit-scrollbar {
        width: 0;
        height: 0;
    }
    .paginationVue {
        width: 100%;
        height: 60px;
    }
    .cancel, .create {
        width: 80px;
        height: 36px;
        border-radius: 5px;
        border: none;
        cursor: pointer;
        text-align: center;
        line-height: 36px;
    }
    .cancel {
        background: transparent;
        border: 1px solid #DCDFE6;
        color: #999;
        line-height: 36px;
    }
    .create {
        background: #0147fd;
        color: #fff;
        margin-left: 10px;
    }
}
</style>
